package com.ruoyi.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.exec.CommandLine;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author 33692
 */

@Slf4j
public class PythonUtil {

    /**
     * 执行 Python 脚本，并传递路径和参数
     * @param scriptPath Python 脚本的路径
     * @param args 传递给 Python 脚本的参数
     */
    public void executePython(String scriptPath, String... args) {
        // 构造命令：python 路径
        String pythonCommand = "python " + scriptPath;  // 或者 python3，根据你的环境
        CommandLine cmdLine = CommandLine.parse(pythonCommand);

        // 添加脚本参数
        for (String arg : args) {
            cmdLine.addArgument(arg);
        }

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            // 将 Python 脚本的输出捕获到 ByteArrayOutputStream
            PumpStreamHandler streamHandler = new PumpStreamHandler(baos);
            DefaultExecutor executor = new DefaultExecutor();
            executor.setStreamHandler(streamHandler);

            // 执行命令
            int exitCode = executor.execute(cmdLine);
            log.info("调用Python脚本的执行结果: {}.", exitCode == 0 ? "成功" : "失败");
            log.info("Python 脚本输出:\n" + baos.toString().trim());
        } catch (ExecuteException e) {
            log.error("执行Python脚本出错，退出码：{}", e.getExitValue());
        } catch (IOException e) {
            log.error("调用Python脚本出错", e);
        }
    }
}
